/**
 * Created by ting.yin on 16/11/3.
 */
angular
  .module('app.service')
  .service('StudentService', StudentService);

StudentService.$inject = ['$http','API','HOST'];
function StudentService($http,API,HOST) {
  var baseUrl = API + 'students';
  this.get = get;
  this.create = create;
  this.save = save;
  this.remove = remove;
  this.list = list;
  this.studentImport = studentImport;
  this.clearAll = clearAll;
  this.studentUpload = studentUpload;

  function get(studentId){
    return $http.get(baseUrl+'/'+studentId);
  }

  function create(student){
    return $http.post(baseUrl,student);
  }

  function save(student){
    return $http.put(baseUrl+"/" + student.id,student);
  }

  function remove(studentId){
    return $http.delete(baseUrl+"/"+studentId);
  }

  function list(params) {
    var url = "?workId="+params.workId+"&page="+params.page+"&size="+params.size;
    if(params.examNumber!=null){
      url = url+"&examNumber="+params.examNumber;
    }
    if(params.name!=null){
      url = url+"&name="+params.name;
    }
    if(params.areaCode!=null){
      url = url+"&areaCode="+params.areaCode;
    }
    if(params.uploadStatus!=null){
      url = url+"&uploadStatus="+params.uploadStatus;
    }
    if(params.isAbsent!=null){
      url = url+"&isAbsent="+params.isAbsent;
    }
    return $http.get(baseUrl+url);
  }

  function clearAll(workId) {
    return $http.delete(baseUrl+"?workId="+workId);
  }

  function studentImport(file,workId,isAbsent){
    //return $http.post('http://localhost:8080/import/students',{'workId':workId,"isAbsent":false,"file":file});
    return $http({
        method:'POST',
        url: HOST+'import/students',
      transformRequest: function (data) {
        var fd = new FormData();
        angular.forEach(data, function (value, key) {
          fd.append(key, value);
        });
        return fd;
      },
        headers: {
          'Content-Type': undefined
        },
        data: {
          "workId":workId,
          "isAbsent":isAbsent,
          "file":file
        }
    })
  }

  function studentUpload(file,studentId,subject,isManual){
    //return $http.post('http://localhost:8080/import/students',{'workId':workId,"isAbsent":false,"file":file});
    if(isManual="undefined"){
      isManual = false;
    }

    return $http({
      method:'POST',
      url: baseUrl+"/"+studentId,
      transformRequest: function (data) {
        var fd = new FormData();
        angular.forEach(data, function (value, key) {
          fd.append(key, value);
        });
        return fd;
      },
      headers: {
        'Content-Type': undefined
      },
      data: {
        "file":file,
        "subject":subject,
        "isManual":isManual
      }
    })
  }
}
